package com.hong.utils;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther: Administrator
 * @Date: 2018/7/21 18:25
 * @Description:
 * 通地countDownLatch来等待线程的结束。
 */
public class CountDownLatchExample1 {
    /**随机数*/
    private static Random random  = new Random(System.currentTimeMillis());
    /**创建一个二个线程的池*/
    private static ExecutorService executor =Executors.newFixedThreadPool(2);
    /**创建一个countDown*/
    private  static final CountDownLatch latch = new CountDownLatch(10);

    /**主线程*/
    public static void main(String[] args) throws InterruptedException {
//        （1）
        final  int[] data = query();
//        （2）
        /**循环进行线程*/
        for (int i =0;i<data.length;i++){
            executor.execute(new SimpleRunnable(data,i, latch));
        }
//        （3）
        /**等待线程结束*/
        latch.await();
        System.out.println("all of work finish done.");
        /**关闭线程 池*/
        executor.shutdown();
    }

    static class SimpleRunnable implements  Runnable{

        private final int[] data;

        private final int index;

        private final CountDownLatch latch;

        public SimpleRunnable(int[] data, int index, CountDownLatch latch) {
            this.data = data;
            this.index = index;
            this.latch = latch;
        }

        public void run() {
            try {
                Thread.sleep(random.nextInt(2000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            int value = data[index];
            if(value%2 == 0){
                data[index]=value * 2;
            }else{
                data[index] =value * 10;
            }
            System.out.println(Thread.currentThread().getName()+" finished.");
            latch.countDown();
        }
    }
    /**数据*/
    private static int[] query(){
        return new int[]{1,2,3,4,5,6,7,8,9,10};
    }


}
